package com.example.jetpackcomposelazycolumn.data.network

import android.util.Log
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitClient {

    companion object {
        private const val baseUrl = "https://anime-pictures.net/"
        private var requestHeader = mutableMapOf<String, MutableMap<String, String>>()

        fun createRetrofitClient(): AdoptMeWebApi {
            return Retrofit.Builder().baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
                .client(initializeRetrofit()).build().create(AdoptMeWebApi::class.java)
        }

        private fun initializeRetrofit(): OkHttpClient {

            val httpClient = OkHttpClient.Builder()

            httpClient.addInterceptor { chain ->
                val originalRequest = chain.request()
                val requestBuilder = originalRequest.newBuilder()

                if (requestHeader.containsKey(originalRequest.url().toString())) {
                    val headers = requestHeader.getValue(originalRequest.url().toString())

                    if (headers.isNotEmpty()) {
                        headers.forEach { entry ->
                            requestBuilder.header(entry.key, entry.value)
                        }
                    }
                }

                val request = requestBuilder.build()
                val response = chain.proceed(request)
                Log.d("Http拦截器-", "Response is : ${response.isSuccessful}")
                Log.d("Http拦截器-", "Response  data : ${response.peekBody(1024)}")
                response
            }

            return httpClient.build()
        }
    }
}